import 'dart:io';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:video_player/video_player.dart';
import 'package:xcite/core/utils/ali.dart';

import '../../core/models/travel_log_model.dart';
import '../../core/models/user_model.dart';
import '../../core/providers/travel_log_provider.dart';
import '../../core/providers/user_provider.dart';
import '../../core/utils/popup_helper.dart';
import '../../core/utils/toast_helper.dart';

class MediaPlaybackDisplayView extends ConsumerStatefulWidget {
  final String videoLogIdentifier;

  const MediaPlaybackDisplayView({super.key, required this.videoLogIdentifier});

  @override
  ConsumerState<MediaPlaybackDisplayView> createState() =>
      _MediaPlaybackDisplayViewState();
}

class _MediaPlaybackDisplayViewState
    extends ConsumerState<MediaPlaybackDisplayView> {
  VideoPlayerController? _videoController;
  bool _isVideoInitialized = false;
  bool _hasError = false;

  @override
  void initState() {
    super.initState();
    _initializeVideoPlayer();
  }

  @override
  void dispose() {
    _videoController?.dispose();
    super.dispose();
  }

  void _initializeVideoPlayer() async {
    try {
      final travelLogNotifier = ref.read(travelLogProvider.notifier);
      final travelLog = travelLogNotifier.getLogById(widget.videoLogIdentifier);

      if (travelLog == null || !travelLog.isVideoType) {
        setState(() {
          _hasError = true;
        });
        return;
      }

      if (travelLog.mediaUrl.startsWith('assets/')) {
        _videoController = VideoPlayerController.asset(travelLog.mediaUrl);
      } else {
        final file = File(travelLog.mediaUrl);
        if (await file.exists()) {
          _videoController = VideoPlayerController.file(file);
        } else {
          setState(() {
            _hasError = true;
          });
          return;
        }
      }

      await _videoController!.initialize();

      setState(() {
        _isVideoInitialized = true;
      });
    } catch (e) {
      setState(() {
        _hasError = true;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    final travelLogNotifier = ref.read(travelLogProvider.notifier);
    final currentUser = ref.watch(currentUserProvider);
    final isLoggedIn = ref.watch(isLoggedInProvider);

    final travelLog = travelLogNotifier.getLogById(widget.videoLogIdentifier);

    if (travelLog == null) {
      return Scaffold(
        backgroundColor: Colors.black,
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(Icons.error_outline, size: 64.sp, color: Colors.white),
              SizedBox(height: 16.h),
              Text(
                'Video not found',
                style: TextStyle(fontSize: 18.sp, color: Colors.white),
              ),
              SizedBox(height: 24.h),
              ElevatedButton(
                onPressed: () => GoRouter.of(context).pop(),
                child: Text('Go Back'),
              ),
            ],
          ),
        ),
      );
    }

    final userNotifier = ref.read(userProvider.notifier);
    final allUsers = userNotifier.getAllDefaultUsers();
    final authorInfo = allUsers.firstWhere(
      (user) => user.id == travelLog.userId,
      orElse: () => UserDataEntity.empty(),
    );

    return Scaffold(
      backgroundColor: Colors.black,
      body: Stack(
        children: [
          _buildVideoBackground(),

          _buildTopNavigationBar(),

          _buildBottomContentInfo(travelLog, authorInfo),

          _buildRightSideLikeButton(travelLog, isLoggedIn, currentUser),
        ],
      ),
    );
  }

  Widget _buildVideoBackground() {
    if (_hasError) {
      return Container(
        width: 1.sw,
        height: 1.sh,
        color: Colors.black,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.error_outline, size: 64.sp, color: Colors.white),
            SizedBox(height: 16.h),
            Text(
              'Failed to load video',
              style: TextStyle(fontSize: 18.sp, color: Colors.white),
            ),
          ],
        ),
      );
    }

    if (!_isVideoInitialized || _videoController == null) {
      return Container(
        width: 1.sw,
        height: 1.sh,
        color: Colors.black,
        child: Center(
          child: CircularProgressIndicator(
            valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
          ),
        ),
      );
    }

    return SizedBox(
      width: 1.sw,
      height: 1.sh,
      child: Stack(
        children: [
          Positioned.fill(
            child: FittedBox(
              fit: BoxFit.cover,
              child: SizedBox(
                width: _videoController!.value.size.width,
                height: _videoController!.value.size.height,
                child: VideoPlayer(_videoController!),
              ),
            ),
          ),

          Positioned.fill(
            child: GestureDetector(
              onTap: () {
                setState(() {
                  if (_videoController!.value.isPlaying) {
                    _videoController!.pause();
                  } else {
                    _videoController!.play();
                  }
                });
              },
              child: Container(
                color: Colors.transparent,
                child:
                    !_videoController!.value.isPlaying
                        ? Center(
                          child: Container(
                            width: 80.w,
                            height: 80.h,
                            decoration: BoxDecoration(
                              shape: BoxShape.circle,
                              color: Colors.transparent,
                            ),
                            child: Icon(
                              AliIcons.iconPlayFill,
                              color: Colors.white,
                              size: 50.sp,
                            ),
                          ),
                        )
                        : null,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildTopNavigationBar() {
    return Positioned(
      top: 0,
      left: 0,
      right: 0,
      child: SafeArea(
        child: Container(
          height: 56.h,
          padding: EdgeInsets.symmetric(horizontal: 16.w),
          child: Row(
            children: [
              Container(
                width: 40.w,
                height: 40.h,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: Colors.black.withValues(alpha: 0.5),
                ),
                child:
                    Icon(
                      Icons.arrow_back_ios_new,
                      color: Colors.white,
                      size: 20.sp,
                    ).center(),
              ).inkWell(onTap: () => GoRouter.of(context).pop()),

              Spacer(),

              Container(
                width: 40.w,
                height: 40.h,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: Colors.black.withValues(alpha: 0.5),
                ),
                child:
                    Icon(
                      AliIcons.iconReport,
                      color: Colors.white,
                      size: 22.sp,
                    ).center(),
              ).inkWell(onTap: () => _showVideoReportDialog()),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildBottomContentInfo(
    TravelLogEntity travelLog,
    UserDataEntity authorInfo,
  ) {
    return Positioned(
      bottom: 0,
      left: 0,
      right: 0,
      child: Container(
        padding: EdgeInsets.only(
          left: 16.w,
          right: 16.w,
          bottom: MediaQuery.of(context).padding.bottom + 20.h,
          top: 20.h,
        ),
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.bottomCenter,
            end: Alignment.topCenter,
            colors: [
              Colors.black.withValues(alpha: 0.8),
              Colors.black.withValues(alpha: 0.4),
              Colors.transparent,
            ],
          ),
        ),
        child: Padding(
          padding: EdgeInsets.only(right: 80.w),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              Row(
                children: [
                  CircleAvatar(
                    radius: 20.r,
                    backgroundImage:
                        authorInfo.avatar.isNotEmpty
                            ? AssetImage(authorInfo.avatar)
                            : null,
                    backgroundColor: Colors.grey[600],
                    child:
                        authorInfo.avatar.isEmpty
                            ? Icon(
                              Icons.person,
                              color: Colors.white,
                              size: 20.sp,
                            )
                            : null,
                  ),
                  SizedBox(width: 12.w),
                  Expanded(
                    child: Text(
                      authorInfo.username.isNotEmpty
                          ? authorInfo.username
                          : 'Unknown User',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 16.sp,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ),
                ],
              ),

              SizedBox(height: 12.h),

              Text(
                travelLog.content,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 14.sp,
                  height: 1.4,
                ),
                maxLines: 3,
                overflow: TextOverflow.ellipsis,
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildRightSideLikeButton(
    TravelLogEntity travelLog,
    bool isLoggedIn,
    UserDataEntity? currentUser,
  ) {
    // 获取最新的旅游日志数据以确保状态同步
    final travelLogNotifier = ref.read(travelLogProvider.notifier);
    final latestTravelLog =
        travelLogNotifier.getLogById(travelLog.logId) ?? travelLog;

    final isLiked =
        isLoggedIn && currentUser != null
            ? latestTravelLog.isLikedByUser(currentUser.id)
            : false;

    return Positioned(
      bottom: MediaQuery.of(context).padding.bottom + 100.h,
      right: 16.w,
      child: Column(
        children: [
          Container(
            width: 50.w,
            height: 50.h,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              color: Colors.transparent,
            ),
            child:
                Icon(
                  AliIcons.iconGood,
                  color: isLiked ? Colors.red : Colors.white,
                  size: 32.sp,
                ).center(),
          ).inkWell(
            onTap: () => _handleLikeAction(travelLog, isLoggedIn, currentUser),
          ),

          SizedBox(height: 8.h),

          Text(
            '${latestTravelLog.likeCount}',
            style: TextStyle(
              color: Colors.white,
              fontSize: 12.sp,
              fontWeight: FontWeight.w600,
            ),
          ),
        ],
      ),
    );
  }

  void _handleLikeAction(
    TravelLogEntity travelLog,
    bool isLoggedIn,
    UserDataEntity? currentUser,
  ) async {
    if (!isLoggedIn || currentUser == null) {
      _showLoginPrompt();
      return;
    }

    try {
      final travelLogNotifier = ref.read(travelLogProvider.notifier);
      final success = await travelLogNotifier.toggleLike(
        travelLog.logId,
        currentUser.id,
      );

      if (mounted && success) {
        setState(() {});

        final updatedLog = travelLogNotifier.getLogById(travelLog.logId);
        final isCurrentlyLiked =
            updatedLog?.isLikedByUser(currentUser.id) ?? false;
        if (isCurrentlyLiked) {
          ToastHelper.success('Liked!', context: context);
        } else {
          ToastHelper.info('Unliked', context: context);
        }
      }
    } catch (e) {
      if (mounted) {
        ToastHelper.error('Operation failed', context: context);
      }
    }
  }

  void _showVideoReportDialog() {
    PopupHelper.showReportDialog(
      context,
      onReportSubmitted: (reportType) async {
        await _handleReportSuccess();
      },
      onCancelPressed: () {},
    );
  }

  Future<void> _handleReportSuccess() async {
    try {
      await Future.delayed(const Duration(milliseconds: 500));

      if (mounted) {
        await Future.delayed(const Duration(milliseconds: 800));

        if (mounted) {
          GoRouter.of(context).pop();
        }
      }
    } catch (e) {
      if (mounted) {
        ToastHelper.error('Failed to submit report', context: context);
      }
    }
  }

  void _showLoginPrompt() {
    PopupHelper.showLoginDialog(
      context,
      onLoginPressed: () {
        GoRouter.of(context).push('/login');
      },
    );
  }
}
